﻿using System.Text.RegularExpressions;
using System.Web.Mvc;
using EPiServer.Common;

namespace JoelAbrahamsson.Web.ModelBinders
{
    public class AuthorModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string authorName = GetValue<string>(bindingContext, "authorName");
            if (string.IsNullOrEmpty(authorName))
                bindingContext.ModelState.AddModelError("authorName", "No name");

            string authorEmail = GetValue<string>(bindingContext, "authorEmail");
            if (string.IsNullOrEmpty(authorEmail))
                bindingContext.ModelState.AddModelError("authorEmail", "No E-mail");

            Regex emailRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
            if (!emailRegex.Match(authorEmail).Success)
                bindingContext.ModelState.AddModelError("authorEmail", "Invalid e-mailaddress");

            string authorUrl = GetValue<string>(bindingContext, "authorUrl");

            if (!bindingContext.ModelState.IsValid)
                return null;

            IAuthor author = new GuestAuthor(authorName, authorEmail, authorUrl);

            return author;
        }

        private T GetValue<T>(ModelBindingContext bindingContext, string key)
        {
            ValueProviderResult valueResult;
            bindingContext.ValueProvider.TryGetValue(key, out valueResult);
            bindingContext.ModelState.SetModelValue(key, valueResult);
            if(valueResult == null)
                return default(T);

            return (T)valueResult.ConvertTo(typeof(T));
        }
    }
}
